package com.wanhe.shoppingcart;

import android.support.v4.app.FragmentActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;

import com.wanhe.base.BasePop;
import com.wanhe.base.model.base.DishesType;
import com.wanhe.base.model.holder.DishTypeHolder;
import com.wanhe.base.model.holder.TableInfoHolder;
import com.wanhe.base.util.DeviceUtil;
import com.wanhe.base.util.SPUtils;
import com.wanhe.base.util.StartActivityManager;
import com.wanhe.base.util.ViewUtil;
import com.wanhe.base.websocket.WebSocketTool;
import com.wanhe.base.websocket.callback.PlaceOrderCallBack;
import com.wanhe.shoppingcart.bean.CartItem;
import com.wanhe.shoppingcart.bean.CartShowItem;
import com.wanhe.shoppingcart.cuiyu.CuiYuOrderFailPop;
import com.wanhe.shoppingcart.manager.CartManager;
import com.wanhe.shoppingcart.manager.ICartChangeObserver;
import com.wanhe.shoppingcart.manager.ICartItem;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by XieZaiWei on 2017/5/9.
 * 购物车
 */

public class CartPop extends BasePop implements View.OnClickListener, OrderPresenter.OnOrderListener,
		ICartChangeObserver, PlaceOrderCallBack {

	private ExpandableListView lv_cart;
	private TextView tv_total_price;
	private TextView tv_order;
	private View v_showLocation;

	//	private CuiYuCartAdapter mCartAdapter;
	private CartAdapter mCartAdapter;
	private OrderPresenter mOrderPresenter;

	public CartPop(FragmentActivity activity, int width, int height) {
		super(activity, LayoutInflater.from(activity).inflate(R.layout.cart_popup_window, null), width, height);
		setOnDismissListener(this);
		setAnimationStyle(R.style.cartPop);
		WebSocketTool.getInstance().setPlaceOrderCallBack(this);
	}


	@Override
	public void initViews() {
		tv_total_price = (TextView) findViewById(R.id.tv_total_price);
		tv_order = (TextView) findViewById(R.id.tv_order);
		lv_cart = (ExpandableListView) findViewById(R.id.lv_cart);

		tv_order.setOnClickListener(this);
		lv_cart.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
			@Override
			public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
				return true;
			}
		});
	}

	@Override
	public void initEvents() {
		CartManager.getInstance().addCartObserver(this);
//		mCartAdapter = new CuiYuCartAdapter(mActivity, R.layout.cui_yu_cart_group,
//				R.layout.cui_yu_item, R.layout.cui_yu_list_item, R.layout.cui_yu_set_meal_item);
		mCartAdapter = new CartAdapter(mActivity,R.layout.cart_group, R.layout.child_item);
		lv_cart.setAdapter(mCartAdapter);
		mOrderPresenter = new OrderPresenter();
		mOrderPresenter.setOnOrderListener(this);
		updataCart();
	}

	public void setShowLocationView(View showLocationView) {
		v_showLocation = showLocationView;
	}


	/**
	 * 更新购物车
	 */
	private void updataCart() {
		tv_total_price.setText("本次点单共计消费/" + CartManager.getInstance().getTotalCost() + "元");
		List<ICartItem> cartItems = CartManager.getInstance().getTotalCartItem();
		//先把菜品进行归类，然后展示
		ArrayList<CartShowItem> arrCartShowItem = new ArrayList<>();
		for (int i = 0; i < cartItems.size(); i++) {
			CartItem cartItem = (CartItem) cartItems.get(i);
			CartShowItem cartShowItem = new CartShowItem();
			DishesType dishesType = DishTypeHolder.getInstance().get(cartItem.getTypeId());
			String title = dishesType.getVCH_TypeName();
			cartShowItem.setTitle(title);
			cartShowItem.setTypeId(cartItem.getTypeId());
			cartShowItem.setTypeNO(dishesType.getCH_TypeNo());
			if (arrCartShowItem.contains(cartShowItem)) {
				arrCartShowItem.get(arrCartShowItem.indexOf(cartShowItem)).getArrCartItem().add(cartItem);
			} else {
				cartShowItem.getArrCartItem().add(cartItem);
				arrCartShowItem.add(cartShowItem);
			}
		}
		if (mCartAdapter != null) {
			mCartAdapter.setData(arrCartShowItem);
			for (int i = 0; i < mCartAdapter.getGroupCount(); i++) {
				lv_cart.expandGroup(i);
			}
		}

	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.tv_order) {
			placeOrder();
		}
	}

	/**
	 * 下单
	 */
	public void placeOrder() {
		int count = CartManager.getInstance().getCount();
		if (count <= 0) {
			Toast.makeText(mActivity, "亲，你还未点菜哦", Toast.LENGTH_SHORT).show();
			return;
		}

		boolean isDom = SPUtils.getIsDemoSchema();
		if (isDom) {
			onOrderSuccess();
			return;
		}

		OrderDialog orderDialog = OrderDialog.newInstance();
		orderDialog.setPresenter(mOrderPresenter);
		orderDialog.show(mActivity.getSupportFragmentManager(), "OrderDialog");

		if (SPUtils.isCheckOrder()) {
			//			OrderDialog orderDialog = new OrderDialog(mContext, mOrderPresenter);
			//			orderDialog.show();
			OrderDialog.newInstance().show(mActivity.getSupportFragmentManager(), "OrderDialog");
		} else {
			//			String tableNum = TableInfoHolder.getInstance().getTableNum();
			//			String peopleCount = String.valueOf(TableInfoHolder.getInstance().getCustomNum());
			//			String jobNumber = WaiterManager.getInstance().getWaiter().getAccount();
			//			String pwd = WaiterManager.getInstance().getWaiter().getPassword();
			//			mOrderPresenter.placeBatchOrder(jobNumber, tableNum, peopleCount, pwd);
		}

	}

	@Override
	public boolean isNeedUpdate() {
		return true;
	}

	@Override
	public void onCartChanged(boolean isAdd) {
		updataCart();
	}

	@Override
	public void onOrderSuccess() {
		Toast.makeText(mActivity, "下单成功", Toast.LENGTH_LONG).show();
		CartManager.getInstance().clear();
		mCartAdapter.clean();
		//以下这些改成用发广播，告诉下单成功
		//				WaiterManager.getInstance().exit();
		//下完一单清空人数
		TableInfoHolder.getInstance().setCustomNum(0);
		ViewUtil.dismissLoadingDialog();
		boolean isDom = SPUtils.getIsDemoSchema();
		if (isDom) {
			StartActivityManager.startActivity(mActivity, StartActivityManager.TableActivity);
		} else {
			StartActivityManager.startActivity(mActivity, StartActivityManager.TableActivity);
		}

		dismiss();
		mActivity.finish();

	}

	@Override
	public void onOrderFail(String msg) {
		Toast.makeText(mActivity, msg, Toast.LENGTH_LONG).show();
	}

	@Override
	public void placeOrderRespon(String msg) {
		try {
			JSONObject respon = new JSONObject(msg);
			int code = respon.getInt("code");
			switch (code) {
				case 0://下单成功
					onOrderSuccess();
					break;

				default:
					Toast.makeText(mActivity, respon.getString("message"), Toast.LENGTH_LONG).show();
					break;
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void showLoading() {
		//		ViewUtil.loadingDialog(mContext);
	}

	@Override
	public void hideLoading() {
		//		ViewUtil.dismissLoadingDialog();
	}

	@Override
	public void onBatchOrderFail(ArrayList<ICartItem> arrOrderSuccess, ArrayList<ICartItem> arrOrderFail) {
		dismiss();
		int width = DeviceUtil.getScreenWidth(mActivity);
		int height = DeviceUtil.getScreenHeight(mActivity);
		CuiYuOrderFailPop orderFailPop = new CuiYuOrderFailPop(mActivity, width, height - 500);
		orderFailPop.showAtLocation(v_showLocation, Gravity.TOP, 0, 0);
		orderFailPop.setData(arrOrderSuccess, arrOrderFail);

	}


	//	/**
	//	 * 下单
	//	 */
	//	public void placeOrder() {
	//		if (SharePUtil.getInstance().isCheck()) {
	//			//			OrderDialog1 orderDialog1 = new OrderDialog1(mActivity, mOrderPresenter);
	//			//			orderDialog1.show();
	//			OrderDialog.newInstance().show(mActivity.getSupportFragmentManager(), "OrderDialog");
	//		} else {
	//			//			String tableNum = TableInfoHolder.getInstance().getTableNum();
	//			//			String peopleCount = String.valueOf(TableInfoHolder.getInstance().getCustomNum());
	//			//			String jobNumber = WaiterManager.getInstance().getWaiter().getAccount();
	//			//			String pwd = WaiterManager.getInstance().getWaiter().getPassword();
	//			//			mOrderPresenter.placeOrder(jobNumber, tableNum, peopleCount, pwd);
	//		}
	//
	//	}
}
